package org.kepler.chat.api.config;

import org.kepler.chat.api.infra.util.Des;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.validation.constraints.NotNull;

/**
 * @author liuke
 * @date 2018/6/26 11:43
 */
@Configuration
public class RedisConfig {

    String strKey = "1002000100010002";

    @Value("${encrypt}")
    boolean encrypt;

    @Value("${redis.maxidle}")
    private int maxIdle;//最大能够保持idel状态的对象数
    @Value("${redis.minidle:10}")
    private int minIdle;
    @Value("${redis.maxtotal}")
    private int maxTotal;//最大分配的对象数
    @Value("${redis.maxwait}")
    private int maxWait;
    @Value("${redis.testOnBorrow}")
    private boolean testOnBorrow;//当调用borrow Object方法时，是否进行有效性检查
    @Value("${redis.timeout}")
    private int timeout;
    private String host;
    private String port;
    private String password;

    @Value("${redis.host}")
    public void setHost(String host) {
        if(encrypt) {
            this.host = Des.Decrypt(host, Des.hex2byte(strKey));
        } else {
            this.host = host;
        }
    }

    @Value("${redis.port}")
    @NotNull
    public void setPort(String port) {
        if(encrypt) {
            this.port = Des.Decrypt("" + port, Des.hex2byte(strKey));
        } else {
            this.port = port;
        }
    }

    @Value("${redis.password}")
    public void setPassword(String password) {
        if(encrypt) {
            this.password = Des.Decrypt(password, Des.hex2byte(strKey));
        } else {
            this.password = password;
        }
    }

    @Bean("jedisPoolConfig")
    public JedisPoolConfig getJedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setTestOnBorrow(testOnBorrow);
        jedisPoolConfig.setTestOnReturn(true);
        jedisPoolConfig.setTestWhileIdle(true);
        jedisPoolConfig.setMaxWaitMillis(maxWait);

        return jedisPoolConfig;
    }

    @Bean("jedisPool")
    public JedisPool getJedisPool() {
        JedisPool jedisPoolConfig = new JedisPool(getJedisPoolConfig(),host,Integer.valueOf(port),timeout,password);
        return jedisPoolConfig;
    }

}
